<?php

namespace App\Jobs\Train\Snap;

use App\Models\Task\SnapTasks\Repositories\Interfaces\SnapTaskRepositoryInterface;
use App\Models\Task\SnapTasks\SnapTask;
use App\Notifications\Train\TrainOrder\SnapExpiredNotify;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class ProcessSnapTaskExpired implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private SnapTask $task_info;
    /**
     * @var mixed|string
     */
    private mixed $out_order_id;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(SnapTask $task_info, $out_order_id = '')
    {
        $this->task_info    = $task_info;
        $this->out_order_id = $out_order_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $isH = $this->task_info->isPaidHighLevel() ? "高速抢票" : "普通抢票";
        Log::info("任务已过期job:{$isH}:{$this->task_info->getTaskId()}");
        $order_info = $this->task_info->getTrainOrderInfo();
        if ($this->out_order_id && $this->out_order_id != $order_info->getOutOrderId()) {
            Log::info("任务已过期job:{$isH}:{$this->task_info->getTaskId()},外部订单id 已变更: {$this->out_order_id}!={$order_info->getOutOrderId()}");
            return;
        }
        $taskRepo = app(SnapTaskRepositoryInterface::class);
        $stop_at  = $taskRepo->getStopAt($this->task_info);
        if (Carbon::parse($stop_at)->lessThan(Carbon::now())) {
            $order_info->notify(new SnapExpiredNotify($order_info));
            $taskRepo->stopTask($this->task_info);
        }
    }
}
